package com.example.e_comm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.e_comm.entity.User;
import com.example.e_comm.mapper.UserMapper;
import com.example.e_comm.service.UserService;
import com.example.e_comm.util.RedisUtil;
import com.example.e_comm.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private TokenUtil tokenUtil;

    // 定义时间单位常量
    private static final long MINUTES = 30;

    @Override
    public boolean register(User user) {
        if (this.count(new QueryWrapper<User>()
                .eq("username", user.getUsername())) > 0) {
            throw new IllegalArgumentException("用户已存在，请替换其他用户名！");
        }
        if (this.count(new QueryWrapper<User>()
                .eq("email", user.getEmail())) > 0) {
            throw new IllegalArgumentException("邮箱已被注册！");
        }
        if (user.getPassword() == null) {
            throw new IllegalArgumentException("密码不能为空！");
        }

        // 修复：确保User实体类有setPassword和setStatus方法
        String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(encryptedPassword);
        user.setStatus(1);
        return this.save(user);
    }

    @Override
    public String login(String username, String password) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new IllegalArgumentException("用户名和密码不能为空！");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        queryWrapper.eq("username", username)
                .eq("password", encryptedPassword)
                .eq("status", 1);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            throw new IllegalArgumentException("用户名或密码错误，请查证后重新操作！");
        }

        String token = tokenUtil.generaToken();

        redisUtil.set("user:token:" + token, user.getId().toString(), MINUTES, TimeUnit.MINUTES);
        return token; // 修复：返回token而不是null
    }

    @Override
    public User getUserByToken(String token) {
        if (!tokenUtil.validaToken(token)) {
            return null;
        }
        Object userIdObj = redisUtil.get("user:token:" + token);
        if (userIdObj == null) {
            return null;
        }
        try {
            Long userId = Long.valueOf(userIdObj.toString());
            return this.getById(userId); // 修复：添加返回语句
        } catch (Exception e) {
            System.err.println("没有找到与这个token适配的User：" + e.getMessage());
            return null;
        }
    }

    @Override
    public boolean logout(String token) {
        User user = getUserByToken(token);
        if (user != null) {
             redisUtil.delete("user:token:" + token);
        }
        return false;
    }
    @Override
    public boolean validateToken(String token) {
        return  redisUtil.hasKay("user:token:"+token);
    }
}